﻿using System;
using System.Collections.Generic;
using System.Text;
using IKEA.FileExchange.Domain.FilePackage;
using Microsoft.SharePoint;
using IKEA.FileExchange.Domain.Files;

namespace IKEA.FileExchange.Domain.DownloadTickets
{
    public static class DownloadTicketManager
    {
        public static SPListItem GetDownloadTicket(string ownerEmail, string packageName, SPWeb spWeb)
        {
            SPQuery q = new SPQuery();

            string queryText = "<Where><And><Eq><FieldRef Name='IKEAFilePackageReference'/><Value Type='Text'>{0}</Value></Eq><Eq><FieldRef Name='DownloadTicketOwnerEmail'/><Value Type='Text'>{1}</Value></Eq></And></Where>";

            q.Query = string.Format(queryText, packageName, ownerEmail);

            SPList fileStore = null;

            fileStore = IKEAFileStoreHelper.GetDownloadTicketsList(spWeb);

            SPListItemCollection tickets = fileStore.GetItems(q);

            if (tickets.Count == 0)
            {
                return null;
            }

            return tickets[0];
        }

        public static Dictionary<string, Guid> CreateDownloadTickets(SPListItem packageItem, SPWeb spWeb, IEnumerable<string> recipients)
        {
            Dictionary<string, Guid> result = new Dictionary<string, Guid>();            

            SPList downloadTicketsList = IKEAFileStoreHelper.GetDownloadTicketsList(spWeb);
            
            foreach (string recipient in recipients)
            {
                SPListItem listItem = downloadTicketsList.Items.Add();
                listItem["Title"] = Guid.NewGuid().ToString();
                listItem[DownloadTicketFieldNames.DownloadTicketOwnerEmail] = recipient;

                SPFieldLookupValue lookupValue = new SPFieldLookupValue(packageItem.ID, packageItem.Title);
                listItem[FileFieldNames.FilePackageReference] = lookupValue;

                listItem.Update();

                listItem["Title"] = listItem.UniqueId.ToString();
                listItem.Update();

                result[recipient] = listItem.UniqueId;
            }

            return result;
        }

        public static Dictionary<string,Guid> CreateDownloadTickets(SPListItem packageItem, SPWeb spWeb)
        {
            FilePackageInformation packageInfo = FilePackageInformationProvider.Extract(packageItem);

            List<string> recipients = packageInfo.GetRecipients();            

            return CreateDownloadTickets(packageItem, spWeb, recipients);
        }
    }
}
